//
//  USTarotCardDetailController.m
//  us
//
//  Created by karry on 2025/5/14.
//

#import "USTarotCardDetailController.h"
#import "USTarotDetailCell.h"
#import "USTarotLoadingView.h"
#import "AIManager.h"
#import "USTarotEmptyCell.h"
#import "USTarotCardShareViewController.h"
#import "USTarotCorrelationCell.h"
#import "USTarotAskLoadingView.h"
@interface USTarotCardDetailController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) NSArray <DTItem *>*items;

@end

@implementation USTarotCardDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.us_tableView.dataSource = self;
    self.us_tableView.delegate = self;
    [self.us_tableView registerNib:[UINib nibWithNibName:@"USTarotDetailCell" bundle:nil] forCellReuseIdentifier:@"USTarotDetailCellId"];
    [self.us_tableView registerNib:[UINib nibWithNibName:@"USTarotEmptyCell" bundle:nil] forCellReuseIdentifier:@"USTarotEmptyCellId"];
    [self.us_tableView registerNib:[UINib nibWithNibName:@"USTarotCorrelationCell" bundle:nil] forCellReuseIdentifier:@"USTarotCorrelationCellId"];

    
    [self startLoading];
    
    [self loadData];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_share_28"] style:UIBarButtonItemStylePlain target:self action:@selector(shareAction:)];
}

- (void)shareAction:(id)sender{
    [USFeedbackTool impactSoft];
    
    USTarotCardShareViewController *vc = [USTarotCardShareViewController new];
    vc.card = self.activeCard;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)loadData{
    [super loadData];
    
    [self setMyAnswer:self.activeCard.answer];
    
}

- (void)setMyAnswer:(NSString *)answer{
    
    self.activeCard.answer = answer;
    
    DTItem *item0 = [DTItem itemWithTitle:@"我" detailTitle:nil image:nil tag:0 identifier:@"me" handle:nil];
    item0.userInfo = self.activeCard;
  
    DTItem *item1 = [DTItem itemWithTitle:@"ta" detailTitle:nil image:nil tag:1 identifier:@"ta" handle:nil];
    
    DTItem *item2 = [DTItem itemWithTitle:@"ta空白" detailTitle:nil image:nil tag:2 identifier:@"empty0" handle:nil];
    
    DTItem *item3 = [DTItem itemWithTitle:@"我们空白" detailTitle:nil image:nil tag:3 identifier:@"empty1" handle:nil];

    DTItem *item4 = [DTItem itemWithTitle:@"我们的相性" detailTitle:nil image:nil tag:4 identifier:@"correlation" handle:nil];

    if (self.relActiveCard) {
        //对方完成视为完成，因为自己没有完成不会来到这个页面
        
        if (self.tarotModel.tarotDetailList.count >= 2 && (self.tarotModel.tarot.tarotAnalysis.length > 0 ||self.tarotModel.tarot.tarotAnalysis.length > 0)) {
            self.items = @[item0,item1,item4];

        }else{
            self.items = @[item0,item1,item3];

        }
    }else {
        self.items = @[item0,item2];
    }
    
  
    
    [self.us_tableView reloadData];
    
}

- (void)requestCorrelation {
    USTarotAskLoadingView *loadView = [USTarotAskLoadingView show];
    loadView.card = self.activeCard;

    @weakify(self)
    @weakify(loadView)

    [AIManager generateTarotReadingWithCardName:self.activeCard.name relCard:self.relActiveCard.name date:[NSDateFormatter localizedStringFromDate:NSDate.date dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle] completion:^(NSString * _Nonnull result, NSError * _Nonnull error) {
        
        @strongify(self)
        [loadView_weak_ dissmiss];
        
        self.tarotModel.tarot.tarotAnalysis = result;
        
        [self setMyAnswer:self.activeCard.answer];

        [self uploadTarotWithAnalysis:result];
        
    }];
}

- (void)uploadTarotWithAnalysis:(NSString *)analysis{
 
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.tarotModel.tarotDetailList.firstObject.tarotId?:@"" forKey:@"tarotId"];
    [params setObject:self.tarotModel.tarotDetailList.firstObject.tarotDetailId?:@"" forKey:@"tarotDetailId"];
    [params setObject:analysis?:@"" forKey:@"tarotAnalysis"];

    [[EMNetWork shareManager] em_post:TarotEdit
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {
        if (!api.success || ![api.data isKindOfClass:[NSDictionary class]]) {
            return;
        }
 
    } fail:^{
 
    }];
}
#pragma mark - 提醒Ta
- (void)remindAction {
 
    //这里塔罗牌的通知，区分提醒去抽取，和我完成了抽取的提醒（action_id可以考虑用传个不传来区分，提醒抽取可以不传，因为固定是取抽取页面）
    NSString *action_title = [NSString stringWithFormat:@"%@提醒你抽取塔罗牌",USUser.user.nickname];
    NSDictionary *ext = @{@"action_id":self.tarotModel.tarotId?:@"",
                          @"action_title":action_title,
                          @"action_content":@"前往抽取"};
    
    [USIMCmdCustomManager imSendCmdWithAction:USIMCmdAction_TarotNotic andExt:ext];

    [USIMCmdCustomManager imSendCustomWithEvent:USIMCmdAction_TarotNotic andCustomExt:ext];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@(USNoticeType_Tarot) forKey:@"type"];
    [param setValue:self.tarotModel.tarotId?:@"" forKey:@"pkId"];
    [param setValue:@"提醒你抽取塔罗牌" forKey:@"content"];
    [param setValue:USUser.user.relUser.userId forKey:@"userId"];
    [param setValue:@(1) forKey:@"shareSpaceFlag"];

    [[EMNetWork shareManager] em_post:NoticeAdd
                               params:param
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
    } fail:^{
        
        
    }];
}

#pragma mark - <UITableViewDelegate,UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    

    DTItem *item = self.items[indexPath.row];
    
    if ([item.identifier isEqualToString:@"me"]) {
        
        USTarotDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USTarotDetailCellId"];
    
        cell.titleLab.text = [NSString stringWithFormat:@"%@·我的",[NSDateFormatter localizedStringFromDate:self.activeCard.date dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle]];
        
        NSString * orientation = self.activeCard.orientation == USTarotCardOrientationReversed?@"逆位":@"正位";

        cell.nameLab.text = [NSString stringWithFormat:@"%@%@", self.activeCard.name,orientation];
    
        cell.cardImageView.image = self.activeCard.cardCover;
   
        NSArray<NSString *> *parts = [self.activeCard.answer componentsSeparatedByString:@"｜｜"];

        if (parts.count != 2) {
            cell.nameLab2.text = nil;
            [cell setAnswer:self.activeCard.answer];
        }else{
            cell.nameLab2.text = parts.firstObject;
            [cell setAnswer:parts.lastObject];
        }

        return cell;
        
    }else  if ([item.identifier isEqualToString:@"ta"]){
        
        USTarotDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USTarotDetailCellId"];
        
        cell.titleLab.text = [NSString stringWithFormat:@"%@·%@的",
                              [NSDateFormatter localizedStringFromDate:self.relActiveCard.date dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle],
                              USUser.user.relUser.nickname];
        
        cell.tagView.backgroundColor = UIColor.us_blueColor;
        
        NSString * orientation = self.relActiveCard.orientation == USTarotCardOrientationReversed?@"逆位":@"正位";

        cell.nameLab.text = [NSString stringWithFormat:@"%@%@", self.relActiveCard.name,orientation];
       
        cell.cardImageView.image = self.relActiveCard.cardCover;
   
        
        NSArray<NSString *> *parts = [self.relActiveCard.answer componentsSeparatedByString:@"｜｜"];

        if (parts.count != 2) {
            cell.nameLab2.text = nil;
            [cell setAnswer:self.relActiveCard.answer];
        }else{
            cell.nameLab2.text = parts.firstObject;
            [cell setAnswer:parts.lastObject];
        }
        
        return cell;
    }else if ([item.identifier isEqualToString:@"correlation"]) {
        
        USTarotCorrelationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USTarotCorrelationCellId"];
    
        cell.imgView1.image = self.activeCard.cardCover;
        cell.imgView2.image = self.relActiveCard.cardCover;
        
        cell.contentLab.text = self.tarotModel.tarot.tarotAnalysis;
        return cell;
    }else if ([item.identifier isEqualToString:@"empty0"] ){
        
        USTarotEmptyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USTarotEmptyCellId"];
        cell.imgV0.image = self.activeCard.cardCover;
        cell.imgV1.image = [UIImage imageNamed:@"Group 2143"];
        
        @weakify(self)
//        UIButtonConfiguration *fig = cell.btn.configuration;
//        fig = [fig copy]; // 防止副作用，复制一份
//        fig.attributedTitle = [[NSAttributedString alloc] initWithString:@"提醒ta"
//                                                               attributes:@{
//                                                                   NSFontAttributeName: [UIFont systemFontOfSize:14]
//                                                               }];
//        cell.btn.configuration = fig; // ✅ 重新设置 configuration
//        [[cell.btn rac_signalForControlEvents:UIControlEventTouchUpInside]
//         subscribeNext:^(__kindof UIControl * _Nullable x) {
//         
//            @strongify(self)
//            
//            [self remindAction];
//        }];
//        [cell.btn us_applyRemindStyleWithTitle:@"提醒Ta"];

//        cell.btn = [UIButton us_remindButtonWithTitle:@"提醒ta"];
         [cell.btn us_addRemindCustomAction:^(UIButton *sender) {
         @strongify(self)
            [self remindAction];
        }];
        return cell;
        
    }else if ([item.identifier isEqualToString:@"empty1"]){
        
        USTarotEmptyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USTarotEmptyCellId"];
        cell.imgV0.image = self.activeCard.cardCover;
        cell.imgV1.image = self.relActiveCard.cardCover;
        
        cell.lab1.text = @"试着占卜一下吧";
        
        UIButtonConfiguration *fig = cell.btn.configuration;
        fig = [fig copy]; // 防止副作用，复制一份
        fig.attributedTitle = [[NSAttributedString alloc] initWithString:@"查看塔罗相容性"
                                                               attributes:@{
                                                                   NSFontAttributeName: [UIFont systemFontOfSize:14]
                                                               }];
        cell.btn.configuration = fig; // ✅ 重新设置 configuration
        // 添加点击事件

        @weakify(self)
        [[cell.btn rac_signalForControlEvents:UIControlEventTouchUpInside]
         subscribeNext:^(__kindof UIControl * _Nullable x) {
         
            @strongify(self)
            
            [self requestCorrelation];
        }];

        return cell;
    }
    
    return [UITableViewCell  new];
    
}

@end
